package com.ssy.lingxi.system.controller;

import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.api.feign.paas.BaseLevelRightCreditControllerFeign;
import com.ssy.lingxi.member.merchant.api.model.vo.paas.BaseLevelConfigVO;
import com.ssy.lingxi.system.dao.MemberEquitiesRepository;
import com.ssy.lingxi.system.dao.MemberGradeRepository;
import com.ssy.lingxi.system.dao.RoleRepository;
import com.ssy.lingxi.system.entity.MemberEquities;
import com.ssy.lingxi.system.entity.MemberGrade;
import com.ssy.lingxi.system.entity.Role;
import com.ssy.lingxi.system.service.MenuService;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 临时接口
 * @author 万宁
 * @version 2.0.0
 * @date 2021-06-12
 */
@RestController
@RequestMapping("/init")
public class InitController {
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private BaseLevelRightCreditControllerFeign baseLevelRightCreditControllerFeign;

    @Resource
    private MemberGradeRepository memberGradeRepository;

    @Resource
    private MemberEquitiesRepository memberEquitiesRepository;

    @Resource
    private RoleRepository roleRepository;

    @Resource
    private MenuService menuService;

    @RequestMapping("/rebuild/role/auth")
    public Wrapper<Void> rebuildAllRoleAuth() {
        return menuService.syncAllRoleBinding();
    }

    @RequestMapping("/level/clear")
    public String clearLevel() {
        List<MemberGrade> existList = memberGradeRepository.findAll();
        if(!CollectionUtils.isEmpty(existList)) {
            for (MemberGrade memberGrade : existList) {
                if(!CollectionUtils.isEmpty(memberGrade.getMemberEquitiesSet())) {
                    memberGrade.getMemberEquitiesSet().clear();
                } else {
                    memberGrade.setMemberEquitiesSet(new HashSet<>());
                }
            }

            memberGradeRepository.saveAll(existList);
        }
        return "ok";
    }

    @RequestMapping("/level/sync")
    public String syncLevel() {
        Wrapper<List<BaseLevelConfigVO>> result = baseLevelRightCreditControllerFeign.listBaseLevelConfig();
        if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
            return "error";
        }

        if(CollectionUtils.isEmpty(result.getData())) {
            return "no data";
        }

        List<MemberEquities> equities = memberEquitiesRepository.findAll();
        if(CollectionUtils.isEmpty(equities)) {
            return "no right";
        }

        List<Role> allRoleList = roleRepository.findAll();
        for (BaseLevelConfigVO datum : result.getData()) {
            if(!datum.getRoleIds().stream().allMatch(r -> allRoleList.stream().anyMatch(role -> role.getId().equals(r)))) {
                return "no role";
            }
        }

        String sql = "delete from cf_member_grade";
        jdbcTemplate.execute(sql);

        sql = "alter sequence cf_member_grade_seq increment 1 restart 1";
        jdbcTemplate.execute(sql);

        List<MemberGrade> memberGradeList = new ArrayList<>();

        for (BaseLevelConfigVO datum : result.getData()) {
            List<Role> roleList = allRoleList.stream().filter(role -> datum.getRoleIds().contains(role.getId())).collect(Collectors.toList());

            for (Role role : roleList) {
                MemberGrade grade = new MemberGrade();
                grade.setCreateTime(System.currentTimeMillis());
                grade.setUpdateTime(System.currentTimeMillis());
                grade.setMemberEquitiesSet(new HashSet<>());
                grade.setRole(role);
                grade.setMemberGrade(datum.getLevel());
                grade.setMemberGradeLabel(datum.getLevelTag());
                grade.setGradeExplain(datum.getRemark());
                grade.setMemberGradeType(datum.getMemberLevelTypeEnum());
                grade.setCreateRoleId(1L);
                grade.setScoreLabel(datum.getScoreTag());
                grade.setMemberEquitiesSet(new HashSet<>(equities));
                grade.setState(1);
                memberGradeList.add(grade);
            }
        }

        memberGradeRepository.saveAll(memberGradeList);
        return "ok";
    }

    /**
     * 初始化菜单属性json中的relationParentCode字段
     * @return 操作结果
     */
    @PostMapping("/menu/init/relationParentCode")
    public Wrapper<Map<Long, String>> initMenuRelationParentCode(Integer source) {
        return menuService.initMenuRelationParentCode(source);
    }
}
